<template>
  <div class="qa-container">
    <el-card>
      <div slot="header">
        <span>应用监测分析</span>
      </div>

      <div class="metric-selector">
        <el-checkbox
          v-model="allSelected"
          @change="handleSelectAll"
        >全选</el-checkbox>

        <el-checkbox-group v-model="selectedMetrics">
          <el-checkbox
            v-for="metric in metrics"
            :key="metric.dictValue"
            :label="metric.dictValue"
          >
            {{ metric.dictLabel }}
          </el-checkbox>
        </el-checkbox-group>
      </div>

      <el-button
        type="primary"
        @click="generateReport"
        :loading="loading"
      >生成报告</el-button>

      <el-button
        v-if="reportContent"
        type="success"
        @click="downloadWord"
      >下载Word报告</el-button>


    </el-card>

    <!-- DeepSeek 问答功能 -->
    <div class="ai-chat-container">
      <div class="chat-history">
        <div v-if="!reportContent" class="empty-chat">
          <img src="@/assets/images/ai-chat.png" alt="AI助手">
          <div class="empty-hit" v-if="!isGenerating">您好！我是智能助手，选择指标点击生成报告吧。</div>
          <div class="progress-container" v-else-if="isGenerating">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: progressPercent + '%' }"></div>
            </div>
            <div class="progress-text">{{ progressPercent }}%</div>
          </div>
        </div>


        <div class="report-box" v-if="reportContent">
          <div v-html="renderedContent"></div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import { generateReport, downloadReport } from '@/api/smart/monitor'
import { getDicts } from '@/api/system/dict/data'
import 'highlight.js/styles/kimbie.light.css'
import markdownit from 'markdown-it'
import hljs from 'highlight.js';
// enable everything
const md = markdownit({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return '<pre><code class="hljs">' +
               hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
               '</code></pre>';
      } catch (__) {}
    }

    return '<pre><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
  }
})

export default {
  data() {
    return {
      metrics: [],
      selectedMetrics: [],
      reportContent: '',
      loading: false,
      allSelected: false,
      isIndeterminate: false,
      chatMessages: [],
      progressPercent: 0,
      isGenerating: false // 新增生成状态标识
    }
  },
  created() {
    this.loadMetrics()
  },
  computed: {
    renderedContent() {
      if (!this.reportContent) return ''
      return md.render(this.reportContent)
    }
  },
  methods: {
    async loadMetrics() {
      try {
        const res = await getDicts('monitor_metric')
        this.metrics = res.data
      } catch (error) {
        this.$message.error('加载指标数据失败')
        console.error(error)
      }
    },
    handleSelectAll(val) {
      this.selectedMetrics = val ? this.metrics.map(item => item.dictValue) : []
    },
    async generateReport() {
      if (this.selectedMetrics.length === 0) {
        this.$message.warning('请至少选择一个指标')
        return
      }

      this.loading = true
      this.isGenerating = true // 开始生成时设置为true
      this.progressPercent = 0

      try {
        const interval = setInterval(() => {
          if (this.progressPercent < 90) {
            this.progressPercent += 10
          }
        }, 500)

        const res = await generateReport({ metrics: this.selectedMetrics })
        this.reportContent = res.data
        this.progressPercent = 100

        clearInterval(interval)
        setTimeout(() => {
          this.isGenerating = false // 生成完成后重置状态
          this.progressPercent = 0
        }, 1000)
      } catch (error) {
        this.$message.error(error.message || '生成报告失败')
        this.isGenerating = false // 出错时重置状态
        this.progressPercent = 0
      } finally {
        this.loading = false
      }
    },
    async downloadWord() {
      try {
        const res = await downloadReport({ content: this.reportContent })
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '监测报告.docx')
        document.body.appendChild(link)
        link.click()
      } catch (error) {
        this.$message.error('下载失败')
      }
    },
    async handleQuestion() {
      if (!this.inputQuestion.trim()) return

      // 添加用户消息
      this.chatMessages.push({
        role: 'user',
        content: this.inputQuestion.trim()
      })

      const question = this.inputQuestion
      this.inputQuestion = ''
      this.responding = true

      // 模拟AI回复
      setTimeout(() => {
        this.chatMessages.push({
          role: 'assistant',
          content: this.generateAnswer(question)
        })
        this.responding = false
        this.scrollToBottom()
      }, 800)
    },

    generateAnswer(question) {
      // 简单模拟AI回复逻辑
      const answers = {
        '指标': '当前支持以下监测指标：\n1. CPU使用率\n2. 内存占用\n3. 磁盘空间\n4. 网络流量',
        '报告': '报告生成通常需要3-5分钟，包含详细的数据分析和可视化图表',
        '默认': '这个问题我需要进一步学习，已记录您的提问'
      }

      return Object.keys(answers).find(key => question.includes(key))
        ? answers[Object.keys(answers).find(key => question.includes(key))]
        : answers['默认']
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$el.querySelector('.chat-history')
        container.scrollTop = container.scrollHeight
      })
    }
  }
}
</script>

<style scoped>
.metric-selector {
  margin-bottom: 20px;
}
.report-box {
  background: #f5f7fa;
  border-radius: 4px;
}

.ai-chat-container {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background: #fff;
}

.chat-history {
  height: 400px;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
  background: #fafafa;
}

.empty-chat {
  text-align: center;
  padding: 60px 0;
  color: #666;

  img {
    width: 120px;
    margin-bottom: 20px;
  }
}

.chat-message {
  margin: 15px 0;
  max-width: 80%;

  &.user {
    margin-left: auto;
    text-align: right;

    .message-content {
      background: #e7f3fe;
      border-radius: 12px 12px 0 12px;
    }
  }

  &.assistant {
    margin-right: auto;

    .message-content {
      background: #fff;
      border-radius: 12px 12px 12px 0;
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    }
  }
}

.message-content {
  display: inline-block;
  padding: 12px 16px;
  margin: 5px 0;

  pre {
    white-space: pre-wrap;
    font-family: inherit;
    margin: 0;
  }
}

.chat-input {
  padding: 15px;
  background: #f5f7fa;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 10px;

  ::v-deep .el-textarea__inner {
    font-size: 14px;
    line-height: 1.5;
  }
}

/* 新增进度条样式 */
.progress-container {
  margin-top: 20px;
  width: 60%;
  margin-left: auto;
  margin-right: auto;
}

.progress-bar {
  height: 12px;
  background: #ebeef5;
  border-radius: 6px;
  overflow: hidden;
  position: relative;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff 0%, #79bbff 100%);
  transition: width 0.3s ease-in-out;
  border-radius: 6px;
}

.progress-text {
  text-align: center;
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
  font-weight: 500;
  transition: all 0.3s;
}

.empty-chat img {
  width: 120px;
  margin-bottom: 20px;
}

/* 保持原有其他样式不变 */
</style>
